/**
 * AreaSelector.jsx
 * 地域选择器
 *
 * created by qiuwei
 * 2016年03月17日
 */

import React from 'react';
import * as AreaSelectorStyle from './AreaSelector.less';

import { PopupWindow, Selector } from '../dumb';
import { CheckPanel } from '../smart';
import { CITY, COUNTY, SCHOOL } from '../../../../constants/area';


export default class AreaSelector extends React.Component {
	static propTypes = {
		selectedCity: React.PropTypes.string,
		selectedCounty: React.PropTypes.string,
		selectedSchool: React.PropTypes.string,
	};

	state = {
		selectedCity: '',
		selectedCounty: '',
		selectedSchool: '',
		view: '', 
		visible: false
	};

	constructor(props) {
		super(props);
	}

	componentWillMount() {
		this.attachPropToState(this.props);
	}

	componentWillReceiveProps(nextProps) {
		this.attachPropToState(nextProps);
	}

	attachPropToState = (props) => {

		let { city, county, school, currentSubView } = props;

		this.setState({
			selectedCity:city.selectedItem.name, 
			selectedCounty:county.selectedItem.name || school.selectedItem.parentName, 
			selectedSchool:school.selectedItem.name,
			view: currentSubView
		});
	}

	handleSelect = () => {

		let { onSelectArea } = this.props;
		onSelectArea && onSelectArea();

		let { visible } = this.state;
		this.setState({ visible: !visible})
	}
	render() {
		let { selectedCity, selectedCounty, selectedSchool, view, visible } = this.state;
		let { children, onSelectArea } = this.props;
		/**
		 * 判断已选地域是否为空，不为空的部分展示出来
		 */
		let primaryText = [];
		if (selectedCity)
			primaryText.push(selectedCity);
		if (selectedCounty)
			primaryText.push(selectedCounty);
		if (selectedSchool)
			primaryText.push(selectedSchool);

		primaryText = primaryText.join('');

		let title = '请选择';
		if (view == CITY)
			title = '请选择城市';
		else if (view == COUNTY)
			title = '请选择区县';
		else if (view == SCHOOL)
			title = '请选择学校';

		return (
			<div className={AreaSelectorStyle.areaSelector} >
				<span>地域 ：</span>
				
				<Selector onClick={this.handleSelect} className="selector">
						{primaryText}
				</Selector>
				<PopupWindow title='请选择' 
					visible={visible} 
					requestClose={()=> this.setState({ visible: false})}>
					{children}
					<button onClick={()=> this.setState({ visible: false})}>关闭</button>
				</PopupWindow>
			</div>
		);
	}
}
